//登录页
import 'dart:async';
import 'package:f_enjoy_plus_community/utils/eventbus.dart';
import 'package:flutter/material.dart';

import '../../utils/http.dart';
import '../../utils/toast.dart';
import '../../utils/token.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  //定时器
  Timer? _timer;
  bool _isCountDown = false; //是否在倒计时
  int _countDownTime = 60; //倒计时时间

  //开启倒计时函数
  void openCountDown() {
    //先判断是否在倒计时
    if (_isCountDown) {
      return;
    }
    //设置开启倒计时
    _isCountDown = true;
    //说明需要倒计时
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      setState(() {
        if (_countDownTime > 0) {
          _countDownTime--;
        } else {
          //倒计时结束
          _isCountDown = false;
          //关闭定时器
          _timer?.cancel();
          //重置秒数
          _countDownTime = 60;
        }
      });
    });
  }

  //获取输入框的值
  //1.通过TextEditingController控制器来获取
  //2.将控制器绑定给输入框
  //3.在页面销毁的时候,还要关闭控制器
  //手机号的输入框
  final TextEditingController _phoneController = TextEditingController();
  //验证码的输入框
  final TextEditingController _codeController = TextEditingController();


  //获取验证码判断
  //1.判断手机号是否为空
  //2.判断手机号是否合法
  //3.都判断成功之后,然后开启倒计时
  //4.然后发请求获取验证码
  void getCode() async {
    //获取输入框中的手机号
    var phone = _phoneController.text;
    //1.判断手机号是否为空
    if (phone.isEmpty) {
      return ToastUtil.showError('请输入手机号');
    }
    //2.判断手机号是否合法
    RegExp reg = RegExp(r'^1[3456789]\d{9}$');
    if (!reg.hasMatch(phone)) {
      return ToastUtil.showError('手机号格式不正确');
    }
    //3.开启倒计时
    openCountDown();

    //4.发请求获取验证码
    final res = await http.get('/code',params:  {'mobile': phone});
    print(res);
    //延迟2秒再回显验证码
    Future.delayed(Duration(seconds: 1), () {
      setState(() {
        _codeController.text = res['data']['code'];
      });
    });
  }

  //登录逻辑处理
  //1.获取手机号是否验证通过(非空和正则)
  //2.获取验证码是否验证通过(非空和正则)
  //3.发请求获取登录结果
  //4.登录成功保存token
  //5.清除定时器
  //6.清除输入框控制器
  //7.登录成功跳转到首页
  void _login() async {
    var phone = _phoneController.text;
    var code = _codeController.text;
    //1.判断手机号是否为空
    if (phone.isEmpty) {
      return ToastUtil.showError('请输入手机号');
    }
    //判断手机号是否合法
    RegExp reg = RegExp(r'^1[3456789]\d{9}$');
    if (!reg.hasMatch(phone)) {
      return ToastUtil.showError('手机号格式不正确');
    }
    //2.判断验证码是否为空
    if (code.isEmpty) {
      return ToastUtil.showError('请输入验证码');
    }
    //判断验证码是否通过正则
    RegExp reg1 = RegExp(r'^\d{6}$');
    if (!reg1.hasMatch(code)) {
      return ToastUtil.showError('验证码格式不正确');
    }
    //3.发请求
    final res = await http.post( '/login', data:{
      'mobile': phone,
      'code': code,
    });
    print(res);
    //4.保存用户信息
    if (res['code'] != 10000) {
      return ToastUtil.showError(res['登录失败!']);
    }
    ToastUtil.showSuccess('登录成功!');
    // TokenManager().removeToken();
    await TokenManager().saveToken(res['data']['token']);
    //5.清除定时器
    _timer?.cancel();
    //6.清除控制器
    _codeController.dispose();
    _phoneController.dispose();

    //7.返回上一页
    // Navigator.popUntil(context, (route) {
    //   return route.settings.name == '/';
    // });
    Navigator.pop(context);

    ToastUtil.showSuccess("登录成功");

    eventBus.fire(RefreshMineEvent());

    //8.重新获取我的页面的个人信息数据
    // event.fire(GetUserInfoEvent());
  }

  @override
  void initState() {
    _phoneController.text = '17605984614';
    // _phoneController.text = '13211112222';
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
    //5.清除定时器
    _timer?.cancel();
    //6.清除控制器
    _codeController.dispose();
    _phoneController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return PopScope(
      canPop: false,
      child: Scaffold(
        backgroundColor: Colors.white,
        appBar: AppBar(
          title: const Text('登录'),
          backgroundColor: Colors.transparent,
          centerTitle: true,
          //隐藏左侧返回按钮箭头
          leading: SizedBox(),
        ),
        body: Container(
          padding: const EdgeInsets.all(20),
          height: MediaQuery.of(context).size.height,
          child: ListView(
            children: [
              Column(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  const Row(
                    children: [
                      Text(
                        '登录',
                        style: TextStyle(
                          fontSize: 25,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 10),
                  const Row(
                    children: [
                      Text('加入享+, 让生活更轻松', style: TextStyle(fontSize: 15)),
                    ],
                  ),
                  const SizedBox(height: 30),
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Expanded(
                        child: TextField(
                          controller: _phoneController, //绑定控制器
                          keyboardType: TextInputType.phone, //输入框的类型
                          maxLength: 11, //输入框可输入的最大长度
                          decoration: InputDecoration(
                            labelText: '手机号',
                            hintText: '请输入手机号',
                          ),
                        ),
                      ),
                      ElevatedButton(
                        style: ElevatedButton.styleFrom(
                          backgroundColor: Colors.white,
                          shadowColor: Colors.transparent,
                          foregroundColor: const Color.fromARGB(
                            255,
                            85,
                            145,
                            175,
                          ),
                          minimumSize: const Size(100, 50),
                        ),
                        onPressed: () {
                          //获取手机号
                          getCode();
                        },
                        child: _isCountDown
                            ? Text('$_countDownTime s后重新获取',style: TextStyle(color:Colors.grey),)
                            : Text('获取验证码'),
                      ),
                    ],
                  ),
                  const SizedBox(height: 8),
                  TextField(
                    controller: _codeController,
                    keyboardType: TextInputType.number,
                    maxLength: 6,
                    decoration: InputDecoration(
                      labelText: '验证码',
                      hintText: '请输入6位验证码',
                    ),
                  ),
                  const SizedBox(height: 8),
                  const Row(
                    children: [
                      Text(
                        '未注册手机号经验证后将自动登录',
                        style: TextStyle(fontSize: 12, color: Colors.grey),
                      ),
                    ],
                  ),
                  const SizedBox(height: 50),
                  Container(
                    width: MediaQuery.of(context).size.width,
                    padding: EdgeInsets.all(10),
                    child: ElevatedButton(
                      style: ElevatedButton.styleFrom(
                        backgroundColor: const Color.fromARGB(
                          255,
                          85,
                          145,
                          175,
                        ),
                        minimumSize: const Size(100, 50),
                      ),
                      onPressed: () {
                        _login();
                      },
                      child: const Text(
                        '登录',
                        style: TextStyle(color: Colors.white, fontSize: 20),
                      ),
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}
